//
//  AppDelegate.m
//  Boss
//
//  Created by admin on 2018/5/31.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "AppDelegate.h"


#import "WYRedPacketMessageController.h"
#import "WYCommentMeController.h"
#import "WYLoginController.h"
#import "WYBaseNavigationController.h"
#import "WYPusherModel.h"
#import "WYForwardMeController.h"
#import "WYCommentMeController.h"
#import "WYFollowMeController.h"
#import "WYMessageDetailController.h"









#import "WYNotificationTooler.h"
#import "WYPusherModel.h"
#import "ZYMainController.h"
#import "IQKeyboardManager.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "YYFPSLabel.h"
#import "WYLoginController.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WeiboSDK.h"
#import "WYSendRedPacketController.h"
#import "WYShareController.h"
#import "WYWaltController.h"
#import "WYBaseNavigationController.h"
#import <AdSupport/AdSupport.h>
#import <JPUSHService.h>
#import <RongIMKit/RongIMKit.h>
#import <RongIMLib/RongIMLib.h>


#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#if BUILD_QQAPIDEMO
#import "TencentOpenAPI/QQApiInterface.h"
#import "QQApiShareEntry.h"
#endif


@interface AppDelegate ()<WXApiDelegate,TencentSessionDelegate,JPUSHRegisterDelegate>{
    TencentOAuth *_oauth;
}
@property(nonatomic ,strong) YYFPSLabel *fpsLabel;
@end
@implementation AppDelegate
-(YYFPSLabel *)fpsLabel{
    if (!_fpsLabel) {
        _fpsLabel = [[YYFPSLabel alloc] initWithFrame:CGRectMake(70, 90, 0, 0)];
        [_fpsLabel sizeToFit];
        _fpsLabel.alpha = 1;
    }
    return _fpsLabel;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:kColorMainColor];
    [WRNavigationBar wr_setDefaultStatusBarStyle:UIStatusBarStyleLightContent];
    // 设置导航栏所有按钮的默认颜色
    [WRNavigationBar wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    // 设置导航栏标题默认颜色
    [WRNavigationBar wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
    
    
    [[RCIMClient sharedRCIMClient] initWithAppKey:RONGCLOUD_IM_APPKEY];
    
    [[RCIMClient sharedRCIMClient] connectWithToken:@"aPphIK/RT72xjZjGWg9aDk14g+QUupV1NSe5CkcXjBrkTZOSqp2DIy7WcPctZsdXo+oclE9oiLszev3m2dH1rJ5eJjzXZr3G"
        success:^(NSString *userId) {
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        } error:^(RCConnectErrorCode status) {
            NSLog(@"登陆的错误码为:%ld", (long)status);
        } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误");
    }];
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
//    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
    
  //  [WYStoreModule storeToken:@"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzY2Q5OTFkNWQxNjA0YWMyOTc2YjgwMzRkNjJlMTExYiIsImF1ZCI6IjE3NSIsInN1YiI6IjEiLCJpYXQiOjE1Mzc2MjQyMjZ9.QKc-SUmzgwgdq5_EJEXgID3XN6aq8N6WzbqivP_es54"];
    
    
    
    
    self.window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    self.window.backgroundColor=[UIColor whiteColor];
    ZYMainController *mvc=[[ZYMainController alloc]init];
    self.window.rootViewController=mvc;
//    WYLoginController *lvc = [[WYLoginController alloc]init];
//    self.window.rootViewController = lvc;
    
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
    
    [self.window makeKeyAndVisible];
   //  [self setKeyBoardManager];
    
   // @"6515aeb7ac4c9ad47019afea01692ea1"
    [WXApi registerApp:@"wx870e1b9a175f40d9"];
    [AMapServices sharedServices].apiKey =@"6515aeb7ac4c9ad47019afea01692ea1";
   _oauth =  [[TencentOAuth alloc] initWithAppId:@"1106972367" andDelegate:self];
    [WeiboSDK enableDebugMode:YES];
    [WeiboSDK registerApp:@"248936818"];
    
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    // 3.0.0及以后版本注册可以这样写，也可以继续用旧的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
    
    WEAKSELF
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            [weakSelf sendRegistrationID:registrationID];
            
            [WYStoreModule storeRegisterId:registrationID];
            
        }
        else{
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    
    
    [JPUSHService crashLogON];
 //   [self initShortcutItems];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    CLLocationManager *manger= [[CLLocationManager alloc]init];
    manger.pausesLocationUpdatesAutomatically = NO;
    // 检测屏幕刷新率
    //[self.window addSubview:self.fpsLabel];
    return YES;
}

//自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"];
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段，key是自己定义的
    
}




-(void)sendRegistrationID:(NSString *)registrationID
{
    
    [WYHttpServer upLoadDateId:registrationID SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
        }
        
        
    }];
    
    
}
-(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    
    UIViewController *myVC;
    
    if ([shortcutItem.type isEqualToString:@"cn.damon.DM3DTouchDemo.opensendRedPacket"]) {
        myVC = [[WYSendRedPacketController alloc]init];
    }else if ([shortcutItem.type isEqualToString:@"cn.damon.DM3DTouchDemo.openShare"]){
        myVC = [[WYShareController alloc]init];
    }else if ([shortcutItem.type isEqualToString:@"cn.damon.DM3DTouchDemo.openSearch"]){
        myVC = [[WYWaltController alloc]init];
    }
//    [self.window.rootViewController.navigationController pushViewController:myVC animated:YES];
//
    //设置当前的VC 为rootVC
   
     WYBaseNavigationController*nav = [[WYBaseNavigationController alloc]initWithRootViewController:myVC];
    //设置当前的VC 为rootVC
    [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    
    
    
    NSLog(@"name:%@\ntype:%@", shortcutItem.localizedTitle, shortcutItem.type);
}

- (void)initShortcutItems {
    
    // if ([UIApplication sharedApplication].shortcutItems.count >= 4)
    //   return;
    
    NSMutableArray *arrShortcutItem = (NSMutableArray *)[UIApplication sharedApplication].shortcutItems;
    
    
    UIApplicationShortcutItem *shoreItem1 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.openSearch" localizedTitle:@"李欣专属我的钱包" localizedSubtitle:nil icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch] userInfo:nil];
    [arrShortcutItem addObject:shoreItem1];
    
//    UIApplicationShortcutItem *shoreItem2 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.openCompose" localizedTitle:@"李欣专属提现" localizedSubtitle:@"" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeCompose] userInfo:nil];
//    [arrShortcutItem addObject:shoreItem2];
    
    UIApplicationShortcutItem *shoreItem32 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.openShare" localizedTitle:@"李欣专属分享" localizedSubtitle:@"" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeShare] userInfo:nil];
    [arrShortcutItem addObject:shoreItem32];
    
    
    UIApplicationShortcutItem *shoreItem33 = [[UIApplicationShortcutItem alloc] initWithType:@"cn.damon.DM3DTouchDemo.opensendRedPacket" localizedTitle:@"李欣专属发布红包" localizedSubtitle:@"" icon:[UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd] userInfo:nil];
    [arrShortcutItem addObject:shoreItem33];
    
    
    [UIApplication sharedApplication].shortcutItems = arrShortcutItem;
    
    NSLog(@"%lu", [UIApplication sharedApplication].shortcutItems.count);
}




- (void)setKeyBoardManager
{
    //IQkey
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setKeyboardDistanceFromTextField:20];
   
    [[IQKeyboardManager sharedManager] setToolbarManageBehaviour:IQAutoToolbarBySubviews];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
//    [[IQKeyboardManager sharedManager] disabledToolbarClasses];
   [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
//    [IQKeyboardManager sharedManager] shouldShowToolbarPlaceholder = NO;
     IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    
    keyboardManager.enableAutoToolbar = NO;
    keyboardManager.shouldShowToolbarPlaceholder = NO;
    
    
    
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
   
    if ([CLLocationManager significantLocationChangeMonitoringAvailable])
        
    {
        
//
//        [[mapCenter manager] stopUpdatingLocation];
//
//        [[mapCenter manage ] startMonitoringSignificantLocationChanges];
        
    }
    
    else
        
    {
        
        NSLog(@"Significant location change monitoring is not available.");
        
    }
    
    
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


//- (void)applicationWillEnterForeground:(UIApplication *)application {
//    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}




- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AlipayResult" object:@{@"result":resultDic}];
            
            
        }];
    }
    [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
        // 解析 auth code
        NSString *result = resultDic[@"result"];
        NSString *authCode = nil;
        if (result.length>0) {
            NSArray *resultArr = [result componentsSeparatedByString:@"&"];
            for (NSString *subResult in resultArr) {
                if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                    authCode = [subResult substringFromIndex:10];
                    break;
                }
            }
        }
        NSLog(@"授权结果 authCode = %@", authCode?:@"");
    }];
    
    
    
    return  [WXApi handleOpenURL:url delegate:self];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [JPUSHService resetBadge];
    
    
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    
    
    
    
    
    return [WXApi handleOpenURL:url delegate:self];
}

-(void)onResp:(BaseResp *)resp
{
    if([resp isKindOfClass:[SendAuthResp class]]){
        
        SendAuthResp *rep = (SendAuthResp *)resp;
        if(rep.errCode == 0){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXAuthorizationSuccess" object:@{@"code":rep.code}];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXAuthorizationError" object:@{@"errorMessage":rep.errStr}];
        }
    }
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *rep = (PayResp *)resp;
        if (rep.errCode ==0) {
             [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPaySuccess" object:nil];
        }else{
            
            
        }
        
        
        
        
        
        
    }
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        
         SendMessageToWXResp *rep = (SendMessageToWXResp *)resp;
        
        if (rep.errCode==0) {
            
            NSLog(@"分享成功");
        }else{
          
            NSLog(@"分享失败");
        }
        
        
        
        
        
    }
    
    
    
    
    
    
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}



#pragma  mark 推送相关
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS6及以下系统，收到通知:%@", [self logDic:userInfo]);
   // [rootViewController addNotificationCount];
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    NSLog(@"iOS7及以上系统，收到通知:%@", [self logDic:userInfo]);
    WYPusherModel *model = [WYPusherModel getPusherModelFromJson:userInfo[@"iosExtras"]];
    [self pushToStateWithJson:model];
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0 || application.applicationState>0) {
        //[rootViewController addNotificationCount];
    }
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [self logDic:userInfo]);
     
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge);
//    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [self logDic:userInfo]);
       // [rootViewController addNotificationCount];
        WYPusherModel *model = [WYPusherModel getPusherModelFromJson:userInfo[@"iosExtras"]];
        [self pushToStateWithJson:model];
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif

// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}
-(void)pushToStateWithJson:(WYPusherModel *)model
{
    if (![self isLogin]) {
        return;
    }
    
    UINavigationController *nav =[self currentNavigationController];

    if ([model.type isEqualToString:@"forward"]) {
        WYForwardMeController *fmvc = [[WYForwardMeController alloc]init];
        [nav pushViewController:fmvc animated:YES];
    }
    
    if ([model.type isEqualToString:@"comment"]) {
        WYCommentMeController *cmc = [[WYCommentMeController alloc]init];
        [nav pushViewController:cmc animated:YES];
    }
    
    if ([model.type isEqualToString:@"reply"]) {
        WYCommentMeController *cmc = [[WYCommentMeController alloc]init];
        [nav pushViewController:cmc animated:YES];
    }
    
    if ([model.type isEqualToString:@"follow"]) {
        WYFollowMeController *cmc = [[WYFollowMeController alloc]init];
        [nav pushViewController:cmc animated:YES];
    }
    
    if ([model.type isEqualToString:@"sys"]) {
        WYMessageDetailController *cmc = [[WYMessageDetailController alloc]init];
        cmc.msgID = model.msgId;
        [nav pushViewController:cmc animated:YES];
    }
    if ([model.type isEqualToString:@"redFinish"]) {
        WYRedPacketMessageController *rvc = [[WYRedPacketMessageController alloc]init];
        WYNearRedPacket *near = [[WYNearRedPacket alloc]init];
        near.redpacketId = model.redPacketId;
        near.redpacketType = @"2";
        near.isReceived = @"1";
        rvc.redPacket = near;
        [nav pushViewController:rvc animated:YES];        
    }
    
    
    
}

-(BOOL)isLogin
{
    NSString *token =[WYStoreModule currentToken];
    if (token.length) {
        return YES;
    }else{
        WYLoginController *loginVc = [[WYLoginController alloc] initWithNibName:@"WYLoginController" bundle:nil];
        WYBaseNavigationController *nav = [[WYBaseNavigationController alloc]initWithRootViewController:loginVc];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:nil];
        return NO;
    }
}
- (UIViewController *)currentViewController
{
    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
//    while (vc.presentedViewController)
//    {
//        vc = vc.presentedViewController;
//
//        if ([vc isKindOfClass:[UINavigationController class]])
//        {
//            vc = [(UINavigationController *)vc visibleViewController];
//        }
//        else if ([vc isKindOfClass:[UITabBarController class]])
//        {
//            vc = [(UITabBarController *)vc selectedViewController];
//        }
//    }
    
//    if ([vc isKindOfClass:[UINavigationController class]])
//        {
//        vc = [(UINavigationController *)vc visibleViewController];
//        }else if ([vc isKindOfClass:[UITabBarController class]])
//        {
//        vc = [(UITabBarController *)vc selectedViewController];
//        }
    
    
    
    
    
    return vc;
}

- (UINavigationController *)currentNavigationController
{
    UIWindow *keyWindow  = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    if ([vc isKindOfClass:[UITabBarController class]]) {
        return [(UITabBarController *)vc selectedViewController];
    }
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return vc;
    }
    if ([vc isKindOfClass:[UIViewController class]]) {
        return vc.navigationController;
    }
    return vc;
}
@end
